<?php
class PeopleProblemsController extends AppController {

	var $name = 'PeopleProblems';
	var $uses = array('PeopleProblem','Problem','Person','Stateproblem','Tag');

    function beforeFilter () {
        parent::beforeFilter();

		// Aplico el Layout segun la Vista o si es AJAX
		if ($this->RequestHandler->isAjax()) {
			$this->layout = 'ajax';
		}else{
			// Cambio la Vista por la del Rol
			$this->layout = strtolower($this->Session->read('VistaActual'));
		}
    }
    
	function index($id_paciente = null, $archivados = null) {
		$this->PeopleProblem->recursive = 0;

		if(!$archivados){
			$peopleproblems = $this->PeopleProblem->find('all', array(
							'conditions' => array(
												'PeopleProblem.client_id' => $this->Session->read('ClientesUsuarioLogueado.id'),
												'PeopleProblem.person_id' => $id_paciente,
												'NOT' => array ('PeopleProblem.staterecord_id' => array('2','3'))
											),
							'order' => array('Stateproblem.orden','PeopleProblem.fecha_origen DESC', 'Problem.name'),
			) );
		}else{ // Para mostrar tambien los registros ARCHIVADOS
			$peopleproblems = $this->PeopleProblem->find('all', array(
							'conditions' => array(
												'PeopleProblem.client_id' => $this->Session->read('ClientesUsuarioLogueado.id'),
												'PeopleProblem.person_id' => $id_paciente,
												'NOT' => array ('PeopleProblem.staterecord_id' => array('2'))
											),
							'order' => array('Stateproblem.orden','PeopleProblem.fecha_origen DESC', 'Problem.name'),
			) );
		}
		$this->set('archivados', $archivados);
		$this->set('peopleproblems', $peopleproblems);
		$this->set('estadoproblemas', $this->Stateproblem ->find('list'));

		$this->set('id_paciente', $id_paciente);
		$this->set('doctores',$this->requestAction('/users/obtenerListadoDoctores/'.$this->Session->read('ClientesUsuarioLogueado.id')) );

		$this->layout = 'ajax';
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid people problem', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('peopleProblem', $this->PeopleProblem->read(null, $id));
	}

	function add($id_paciente = null) {
		if (!empty($this->data)) {
			$this->PeopleProblem->create();

			// Si no se selecciono ningún problema de la lista y tampoco se escribio un problema nuevo
			if ($this->data['PeopleProblem']['problem_id'] == "0" AND $this->data['Problem']['name'] == "") { 
				$this->Session->setFlash(__('Debe seleccionar un Problema o escribir uno nuevo...', true));
				$this->redirect('/people/view/'.$this->data['PeopleProblem']['person_id'].'/2');
			}

			// Si no se selecciono ningún problema de la lista y se escribio un problema nuevo
			if ($this->data['PeopleProblem']['problem_id'] == "0" AND $this->data['Problem']['name'] <> "") { 

				$this->Problem->create();

				$this->Problem->set(array(
					'name' => $this->data['Problem']['name'],
					'user_id' => $this->Auth->user('id'),
				));
				// Grabo el nuevo Problema
				$this->Problem->save();

				// Obtengo el ID cargado
				$this->data['PeopleProblem']['problem_id'] = $this->Problem->id;
			}


			// Seteo datos que no vienen del Formulario
			$this->PeopleProblem->set(array(
				'client_id' => $this->Session->read('ClientesUsuarioLogueado.id'),
				'user_id' => $this->Auth->user('id'),
			));


			if ($this->PeopleProblem->save($this->data)) {
				$this->Session->setFlash(__('Se ha asociado el problema al paciente', true));
				$this->redirect('/people/view/'.$this->data['PeopleProblem']['person_id'].'/2');
			} else {
				$this->Session->setFlash(__('No se pudo asociar el problema al paciente. Por favor, intente nuevamente.', true));
			}
		}

		if (!$id_paciente) {
			exit;
		}

		$people = $this->Person->find('list', array(
						'conditions' => array('Person.id' => $id_paciente),
						'fields' => array('Person.id', 'Person.full_name')
		) );

//		$problems = $this->Problem->find('list');
		$stateproblems = $this->Stateproblem->find('list', array(
							'order' => 'Stateproblem.orden',
		) );

		$tags = $this->PeopleProblem->Tag->find('list');
		$this->set('id_paciente', $id_paciente);
		$this->set(compact('people', 'problems', 'stateproblems','tags'));
	}

	function edit($id = null,$id_paciente = null) {

		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid people problem', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {

			// Seteo datos que no vienen del Formulario
			$this->PeopleProblem->set(array(
				'user_id' => $this->Auth->user('id'),
			));


			if ($this->PeopleProblem->save($this->data)) {
				$this->Session->setFlash(__('El problema asociado al paciente se ha modificado', true));
				$this->redirect('/people/view/'.$this->data['PeopleProblem']['person_id'].'/2');
			} else {
				$this->Session->setFlash(__('No se pudo modificar el problema asociado al paciente. Por favor, intente nuevamente.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->PeopleProblem->read(null, $id);
		}

		if (!$id_paciente) {
			exit;
		}

		$people = $this->Person->find('list', array(
						'conditions' => array('Person.id' => $id_paciente),
						'fields' => array('Person.id', 'Person.full_name')
		) );
		$this->set('id_paciente', $id_paciente);
//		$problems = $this->Person->Problem->find('list');

		$problems = $this->Problem->query(
			"SELECT 
				Problem.id, Problem.name
			FROM 
				people_problems AS PeopleProblem 
				INNER JOIN problems AS Problem ON Problem.id = PeopleProblem.problem_id
			WHERE
				PeopleProblem.id =  '$id'
			"
		);


		$stateproblems = $this->Stateproblem->find('list');
		$tags = $this->PeopleProblem->Tag->find('list');
		$this->set(compact('people', 'problems', 'stateproblems','tags'));
	}

	function editTag($id = null) {

		if (!empty($this->params['form']) AND $id){

			$this->PeopleProblem->id = $id;

			// Si está marcado
			if($this->params['form']['estado']){
				$valor_guardar = 1; // TAG IMPORTANTE
			}else{
				$valor_guardar = NULL;
			}

			// Si lo pudo grabar
			if ($this->PeopleProblem->saveField('tag_id',$valor_guardar)){
				echo "S";
			}else{ // Si no pudo
				echo "N";
			}
		}

		$this->autoRender=false;
	}


	function archivar($id = null, $id_paciente = null, $estado = null) {
		if (!$id) {
			$this->Session->setFlash(__('Problema no valida', true));
			$this->redirect('/dashboards');
		}

		if (!$id_paciente) {
			$this->Session->setFlash(__('Paciente no valido', true));
			$this->redirect('/dashboards');
		}

		if (!$estado) {
			$this->Session->setFlash(__('Estado no valido', true));
			$this->redirect('/dashboards');
		}

		$this->PeopleProblem->id = $id;
		$this->PeopleProblem->set(array(
			'staterecord_id' =>  $estado,
			'user_id' => $this->Auth->user('id'),
		));

		if ($this->PeopleProblem->save()) {
			$this->Session->setFlash(__('El Problema fue procesado.', true));
			$this->redirect('/people/view/'.$id_paciente.'/2');
		}
		$this->Session->setFlash(__('El Problema no pudo ser procesado', true));
		$this->redirect('/people/view/'.$id_paciente.'/2');
	}

	function cambiarestado() {

		$this->PeopleProblem->id = $this->params['form']['draggedid'];
		$this->PeopleProblem->saveField('stateproblem_id',$this->params['form']['zona']);

		$this->autoRender=false;
  	}


	function existeProblema($id_paciente = null, $id_problema = null){

		if (!$id_paciente) {
			return 1;
		}

		if (!$id_problema) {
			return 1;
		}


		$problemaspaciente = $this->PeopleProblem->find('all', array(
						'conditions' => array(
											'PeopleProblem.client_id' => $this->Session->read('ClientesUsuarioLogueado.id'),
											'PeopleProblem.person_id' => $id_paciente,
											'PeopleProblem.problem_id' => $id_problema,
										),
						'fields' => array('Problem.id', 'Problem.name')
		) );


		// Si el Problema es Nuevo
		if(empty($problemaspaciente)){
			return 0;
		}else{
			return 1;
		}
	}

	function mostrarestado($id_paciente = null, $id_estado = null, $archivados = null) {
		$this->PeopleProblem->recursive = 0;

		if(!$id_estado){
			exit;
		}

		if(!$archivados){
			$peopleproblems = $this->PeopleProblem->find('all', array(
							'conditions' => array(
												'PeopleProblem.client_id' => $this->Session->read('ClientesUsuarioLogueado.id'),
												'PeopleProblem.person_id' => $id_paciente,
												'PeopleProblem.stateproblem_id' => $id_estado,
												'NOT' => array ('PeopleProblem.staterecord_id' => array('2','3'))
											),
							'order' => array('Stateproblem.orden','PeopleProblem.fecha_origen DESC', 'Problem.name'),
			) );
		}else{ // Para mostrar tambien los registros ARCHIVADOS
			$peopleproblems = $this->PeopleProblem->find('all', array(
							'conditions' => array(
												'PeopleProblem.client_id' => $this->Session->read('ClientesUsuarioLogueado.id'),
												'PeopleProblem.person_id' => $id_paciente,
												'PeopleProblem.stateproblem_id' => $id_estado,
												'NOT' => array ('PeopleProblem.staterecord_id' => array('2'))
											),
							'order' => array('Stateproblem.orden','PeopleProblem.fecha_origen DESC', 'Problem.name'),
			) );
		}
		$this->set('archivados', $archivados);
		$this->set('peopleproblems', $peopleproblems);
		$this->set('estadoproblemas', $this->Stateproblem ->find('list'));
		$this->set('id_paciente', $id_paciente);
		$this->set('id_estado', $id_estado);

		$this->layout = 'ajax';
	}
}
?>